package com.jnu.myaccount.function.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jnu.myaccount.DetailActivity;
import com.jnu.myaccount.MainActivity;
import com.jnu.myaccount.R;
import com.jnu.myaccount.RecordActivity;
import com.jnu.myaccount.data.Data;
import com.jnu.myaccount.data.DataBank.DataBank;
import com.jnu.myaccount.data.Money;
import com.jnu.myaccount.databinding.FragmentHomeBinding;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    private static Context ct;

    public static Double itemAllMoney;//总资产
    public static Double itemAllPaid;//本月支出
    public static Double itemAllEarn;//本月收入
    private View view;//定义view用来设置fragment的layout
    public RecyclerView mCollectRecyclerView;//定义RecyclerView
    private static ArrayList<Data> goodsEntityList = new ArrayList<Data>();//定义以Data实体类为对象的数据集合 
    private CollectRecycleAdapter mCollectRecyclerAdapter;//自定义recyclerveiw的适配器

    private TextView mitemAllMoney;
    private TextView mitemAllPaid;
    private TextView mitemAllEarn;

    private DataBank mDataBank;
    private Money mMoney;

   public static int mark_num=-1;//称之为 添加数据的开关

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        ct=getContext();

        //获取fragment的layout
        view = inflater.inflate(R.layout.fragment_home, container, false);
        mitemAllMoney = (TextView) view.findViewById(R.id.current_money);
        mitemAllPaid = (TextView) view.findViewById(R.id.current_paid);
        mitemAllEarn = (TextView) view.findViewById(R.id.current_earn);
        //接收部分(在fragment里面接收）
        Bundle bundle = getActivity().getIntent().getExtras();//在这里去处理传过来的数据
        if(bundle!=null&&mark_num==-1) {
            Serializable serializable = bundle.getSerializable("DataInfo");
            if (serializable != null && serializable instanceof Data) {
                //goodsEntityList.add(new Data("111",20.0,"none",new Date(),R.drawable.home));
                Data g = (Data) serializable;

                if(bundle.getString("type").equals("paidEdit"))//修改数据
                {
                    Log.i("type",bundle.getString("type"));
                    int i=bundle.getInt("position");
                    goodsEntityList.set(i,g);
                }
                else if(bundle.getString("type").equals("add")){//添加数据

                    goodsEntityList.add(g);
                }
                Collections.sort(goodsEntityList);
                initRecyclerView();
                mitemAllMoney.setText(itemAllMoney + "元");
                mitemAllPaid.setText(itemAllPaid + "元");
                mitemAllEarn.setText(itemAllEarn + "元");
                mDataBank=new DataBank(getActivity());
                mMoney=new Money(itemAllMoney,itemAllPaid,itemAllEarn);
                mDataBank.saveMoney(mMoney);
                mDataBank.saveData(goodsEntityList);
                mark_num=0;
            }
        }
        else {
            //初始化数据
            initData();
            //对recycleview进行配置
            initRecyclerView();
            mitemAllMoney.setText( itemAllMoney+ "元");
            mitemAllPaid.setText(itemAllPaid + "元");
            mitemAllEarn.setText(itemAllEarn+ "元");

        }

        return view;

    }

    private void initData() {
        mDataBank=new DataBank(getActivity());
        if(mDataBank.loadData()!=null) {
            goodsEntityList = mDataBank.loadData();
        }
        else{
            goodsEntityList=null;
        }
        mMoney= mDataBank.loadMoney();
        if(mMoney!=null) {
           itemAllMoney = mMoney.getAllMoney();
            itemAllEarn = mMoney.getAllEarn();
            itemAllPaid = mMoney.getAllPaid();
        }
        else {
           itemAllMoney = 0.0;
            itemAllEarn = 0.0;
            itemAllPaid = 0.0;
        }
    }


    /**
     * TODO 对recycleview进行配置
     */
    private void initRecyclerView() {
        //获取RecyclerView
        mCollectRecyclerView=(RecyclerView)view.findViewById(R.id.recyle_view);
        //创建adapter
        mCollectRecyclerAdapter = new CollectRecycleAdapter(getActivity(),goodsEntityList);
        //给RecyclerView设置adapter
        int spacingInPixels = 8;
        mCollectRecyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));

        mCollectRecyclerView.setAdapter(mCollectRecyclerAdapter);
        //RecycleView 增加边距

        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        mCollectRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
       mCollectRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL));

        //RecyclerView中没有item的监听事件，需要自己在适配器中写一个监听事件的接口。参数根据自定义
        mCollectRecyclerAdapter.setOnItemClickListener(new CollectRecycleAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, Data data,int position) {
                //此处进行监听事件的业务处理
                Toast.makeText(getActivity(),data.getItemName(),Toast.LENGTH_SHORT).show();
                Intent intent=new Intent(getActivity(), DetailActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("type","show");//表明这是一条用来展示的intent
                bundle.putSerializable("DataInfo", data);
                bundle.putInt("position", position);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    public static class CollectRecycleAdapter extends RecyclerView.Adapter<CollectRecycleAdapter.myViewHodler>{
        private static Context mContext;
        private ArrayList<Data> goodsEntityList;

        //创建构造函数
        public CollectRecycleAdapter(Context context, ArrayList<Data> goodsEntityList) {
            //将传递过来的数据，赋值给本地变量
            this.mContext = context;//上下文
            this.goodsEntityList = goodsEntityList;//实体类数据ArrayList
        }

        public static  Context getContext(){//在静态类内部使用静态的实例化的上下文，即activity
            return mContext;
        }
        /**
         * 创建viewhodler，相当于listview中getview中的创建view和viewhodler
         *
         * @param parent
         * @param viewType
         * @return
         */
        @Override
        public myViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {
            //创建自定义布局
            View itemView = LayoutInflater.from(mContext).inflate(R.layout.layout_home_item, parent, false);
            return new myViewHodler(itemView);
        }

        /**
         * 绑定数据，数据与view绑定
         *
         * @param holder
         * @param position
         */
        @Override
        public void onBindViewHolder(myViewHodler holder, int position) {
            //根据点击位置绑定数据
            Data data = goodsEntityList.get(position);
            holder.mitemName.setText(data.getName());//获取实体类中的name字段并设置
            holder.mitemCost.setText("￥"+data.getCost()+"元");//获取实体类中的cost字段并设置
            holder.mImageView.setImageResource(data.getPictureID());
            holder.mMark.setText(data.getItemMark());
            holder.mDate.setText(data.getTime());
        }

        /**
         * 得到总条数
         *
         * @return
         */
        @Override
        public int getItemCount() {
            return goodsEntityList.size();
        }

        //自定义viewhodler
        private class myViewHodler extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {

            private TextView mitemName;
            private TextView mitemCost;
            private ImageView mImageView;
            private TextView mMark;
            private TextView mDate;


            public myViewHodler(View itemView) {
                super(itemView);
                mitemName = (TextView) itemView.findViewById(R.id.item_type_tv_title);
                mitemCost = (TextView) itemView.findViewById(R.id.item_mainlv_tv_money);
                mImageView=itemView.findViewById(R.id.item_type_iv);
                mMark=itemView.findViewById(R.id.item_type_tv_beizhu);
                mDate=itemView.findViewById(R.id.item_mainlv_tv_time);

                //点击事件放在adapter中使用，也可以写个接口在activity中调用
                itemView.setOnCreateContextMenuListener(this);//从RecyclerView的Adapter入手，在Adapter的ViewHolder中为每个itemView设置setOnLongClickListener监听，然后在长按监听回调中设置当前的position，为每个itemView设置setOnCreateContextMenuListener监听，通过上面记录的position来执行相应的动作。
                //方法一：在adapter中设置点击事件
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //可以选择直接在本位置直接写业务处理
                        //Toast.makeText(context,"点击了xxx",Toast.LENGTH_SHORT).show();
                        //此处回传点击监听事件//
                        if(onItemClickListener!=null){
                            onItemClickListener.OnItemClick(v, goodsEntityList.get(getLayoutPosition()),getLayoutPosition());//传过去的data是点击的位置对应的记账对象
                        }
                    }
                });


            }

            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View v, ContextMenu.ContextMenuInfo menuInfo) {//添加长摁式子菜单实现数据的增删改查
                int position = getAdapterPosition();//从onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)方法传递进来的menuInfo中获取到相应的position信息。
                MenuItem add = contextMenu.add(Menu.NONE, 1, 1, "Add");
                MenuItem edit = contextMenu.add(Menu.NONE, 2, 2, "Edit");
                MenuItem delete = contextMenu.add(Menu.NONE, 3, 3, "Delete");

                add.setOnMenuItemClickListener(this);
                edit.setOnMenuItemClickListener(this);
                delete.setOnMenuItemClickListener(this);

            }

            public boolean onMenuItemClick(MenuItem menuItem) {
                int position=getAdapterPosition();
                Intent intent;

                switch(menuItem.getItemId()){
                    case 1://添加记录
                        intent=new Intent(getContext(),RecordActivity.class);
                        getContext().startActivity(intent);
                        break;

                        case 2://修改记录
                            intent=new Intent(getContext(),RecordActivity.class);
                            Bundle bundle=new Bundle();
                            Data mDate=goodsEntityList.get(position);//将当前的data对象传给record_activity
                            bundle.putSerializable("DataInfo",mDate);
                            bundle.putInt("position",position);
                            if(mDate.itemCost<=0){
                                bundle.putString("type","Paid");//这条额外的信息标识这是一条支出信息
                                itemAllPaid=itemAllPaid-mDate.itemCost;
                            }
                            else{
                                bundle.putString("type","Income");//这条额外的信息标识这是一条收入信息
                               itemAllEarn=itemAllEarn-mDate.itemCost;
                            }
                            Log.i("position1",position+"");
                            itemAllMoney=itemAllMoney-mDate.itemCost;
                            intent.putExtras(bundle);
                           mContext.startActivity(intent);

                        break;

                    case 3://删除记录
                        AlertDialog.Builder alertDB = new AlertDialog.Builder(getContext());
                        alertDB.setPositiveButton(getContext().getResources().getString(R.string.string_confirmation), (dialogInterface, i) -> {
                            Data mData=goodsEntityList.get(position);//将当前的data对象传给record_activity
                            itemAllMoney-=mData.itemCost;
                            if(mData.itemCost>0){
                                itemAllEarn-=mData.itemCost;
                            }
                            else{
                                itemAllPaid-=mData.itemCost;
                            }
                            goodsEntityList.remove(position);
                            DataBank mDataBank=new DataBank(getContext());
                            Money mMoney=new Money(itemAllMoney,itemAllPaid,itemAllEarn);
                            mDataBank.saveMoney(mMoney);
                            mDataBank.saveData(goodsEntityList);
                            notifyItemRemoved(position);
                            Intent intent1=new Intent(getContext(), MainActivity.class);
                            mContext.startActivity(intent1);
                        });
                        alertDB.setNegativeButton(getContext().getResources().getString(R.string.string_cancel), (dialogInterface, i) -> {

                        });
                        alertDB.setMessage(getContext().getResources().getString(R.string.string_confirm_delete) +goodsEntityList.get(position).getName()+"？");
                        alertDB.setTitle(getContext().getResources().getString(R.string.hint)).show();

                        break;
                }

                return false;
            }

        }


        /**
         * 设置item的监听事件的接口
         */
        public interface OnItemClickListener {
            /**
             * 接口中的点击每一项的实现方法，参数自己定义
             *
             * @param view 点击的item的视图
             * @param data 点击的item的数据
             */
            public void OnItemClick(View view, Data data,int position);
        }

        //需要外部访问，所以需要设置set方法，方便调用
        private OnItemClickListener onItemClickListener;

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }


    }

    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;

            // Add top margin only for the first item to avoid double space between items
            if (parent.getChildPosition(view) == 0)
                outRect.top = space;
        }

    }
}